package com.spring.cloud.weather.collection.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/3/18
 */
@Service
public class WeatherDataCollectionServiceImpl implements WeatherDataCollectionService {

    private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";

    private static final long TIME_OUT = 30 * 60L;

    private static final String REDIS_NAMESPACE_WEATHER = "weather:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据城市ID同步天气
     *
     * @param cityId cityId
     */
    @Override
    public void syncDataByCityId(String cityId) {
        String uri = WEATHER_URI + "citykey=" + cityId;
        this.getWeatherDataAndSaveToRedis(uri);
    }

    /**
     * 把天气数据放在缓存
     * @param uri uri
     */
    private String getWeatherDataAndSaveToRedis(String uri) {
        String key = REDIS_NAMESPACE_WEATHER + uri;
        String strBody = null;
        ValueOperations<String, String>  ops = redisTemplate.opsForValue();

        // 调用服务接口来获取
        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }

        // 数据写入缓存
        if (strBody != null) ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);

        return strBody;
    }
}
